package com.websocket.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.sockjs.transport.session.WebSocketServerSockJsSession;

import com.system.comm.utils.FrameMapUtil;
import com.websocket.pojo.User;

@Component
public class WebSocketData {

	private Map<String, User> userData = new HashMap<String, User>();
	// 订阅行情的用户
	private List<String> quotationUser = new ArrayList<String>();

	/**
	 * 添加用户
	 * @param user
	 */
	public void addUser(String token, WebSocketSession webSocketSession) {
		String sessionId = getSessionId(webSocketSession);
		User user = new User();
		user.setToken(token);
		user.setWebSocketSession(webSocketSession);
		user.setSessionId(sessionId);
		userData.put(sessionId, user);
	}
	/**
	 * 添加行情用户
	 * @param sessionId
	 */
	private void addQuotationUser(String sessionId) {
		if (!quotationUser.contains(sessionId)) {
			quotationUser.add(sessionId);
		}
	}
	/**
	 * 取消行情用户
	 * @param sessionId
	 */
	private void removeQuotationUser(String sessionId) {
		if (quotationUser.contains(sessionId)) {
			quotationUser.remove(sessionId);
		}
	}
	
	/**
	 * 获取行情用户列表
	 * @return
	 */
	public List<String> getQuotationUserList() {
		return quotationUser;
	}
	/**
	 * 根据token获取用户
	 * @param token
	 * @return
	 */
	public User getUser(String sessionId) {
		return userData.get(sessionId);
	}
	
	/**
     * 获取sessionId
     */
    public String getSessionId(WebSocketSession session) {
        if (session instanceof WebSocketServerSockJsSession) {
            // sock js 连接
            try {
                return ((WebSocketSession) FieldUtils.readField(session, "webSocketSession", true)).getId();
            } catch (IllegalAccessException e) {
                throw new RuntimeException("get sessionId error");
            }
        }
        return session.getId();
    }
    /**
     * 移除用户
     * @param session
     */
	public void removeUser(WebSocketSession session) {
		String sessionId = getSessionId(session);
		userData.remove(sessionId);
		quotationUser.remove(sessionId);
	}
	/**
	 * 订阅信息
	 * @param session 
	 * @param data
	 */
	public void subscribe(WebSocketSession session, Map<String, Object> data) {
		Integer subscribeQuotation = FrameMapUtil.getInteger(data, "subscribeQuotation");
		if (subscribeQuotation != null) {
			String sessionId = getSessionId(session);
			if (subscribeQuotation == 1) {
				// 订阅
				addQuotationUser(sessionId);
			} else {
				removeQuotationUser(sessionId);
			}
		}
	}
	/**
	 * 订阅外的业务操作
	 * @param session
	 * @param data
	 */
	public void other(WebSocketSession session, Map<String, Object> data) {
		// TODO Auto-generated method stub
		
	}
}
